package com.task.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.internal.ws.util.xml.CDATA;
import com.task.common.entity.custom.Item;
import com.task.common.util.excelstyle.CustIExcelExportStyler;
import com.task.common.util.model.FieldUtil;
import com.task.common.util.string.StringUtils;
import com.task.mapper.ItemMapper;
import com.task.service.IItemService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Huzz
 * @since 2022-05-21
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Override
    public boolean deleteItem(Integer id) {

        return itemMapper.deleteById(id) >0;
    }

    @Override
    public void exportItem(HttpServletRequest request, HttpServletResponse response, Item itemModel) {
        QueryWrapper<Item> itemQueryWrapper = getItemQueryWrapper(itemModel);

        List<Item> data = this.baseMapper.selectItemList(itemQueryWrapper);



        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("账单业务列表");
        exportParams.setSheetName("项目管理");
        // 设置样式
        exportParams.setStyle(CustIExcelExportStyler.class);

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Item.class, data);

        String fileName = String.format("项目管理_%d.xls", System.currentTimeMillis());
        response.setHeader("Content-Disposition", "attachment;Filename=" + fileName);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Map<String, String>> importItem(MultipartFile multipartFile) {
        List<Map<String, String>> resultData = new ArrayList<>();

        List<Item> list = new ArrayList<>();
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(2);
        try {
            InputStream inputStream = multipartFile.getInputStream();
            list = ExcelImportUtil.importExcel(inputStream, Item.class, importParams);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.isEmpty()) {
            Map<String, String> result = new HashMap<>();
            result.put("ERROR", "导入失败, 请检查文件格式后重试");
            resultData.add(result);
            return resultData;
        }
        if (this.saveBatch(list)) {
            Map<String, String> result = new HashMap<>();
            result.put("OK", "导入成功");
            resultData.add(result);
            return resultData;
        }
        return resultData;
    }

    @Override
    public IPage findItemList(Integer pageNum, Integer pageSie, Item model) {
        QueryWrapper<Item> wrapper = getItemQueryWrapper(model);

        return itemMapper.selectItemList(new Page<>(pageNum, pageSie), wrapper);
    }

    /**
     * 查询条件拼接
     * @param model
     * @return
     */
    private QueryWrapper<Item> getItemQueryWrapper(Item model) {
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(model.getName())) {
            wrapper.lambda().eq(Item::getName, model.getName());
        }
        if (null != model.getStatus()) {
            wrapper.lambda().eq(Item::getStatus, model.getStatus());
        }
        if (!StringUtils.isEmpty(model.getDescription())) {
            wrapper.lambda().like(Item::getDescription, model.getDescription());
        }
        return wrapper;
    }

    @Override
    public boolean updateItem(Integer id, Item itemModel) {
        itemModel.setId(id);
        FieldUtil.setUpdateField(itemModel);
        return itemMapper.updateById(itemModel) > 0;
    }

    @Override
    public boolean createItem(Item itemModel) {
        FieldUtil.setCreatedAndUpdateField(itemModel);
        return itemMapper.insert(itemModel) > 0;
    }
}
